using B.S.XZYData.Api.Wrter.Application.Command.Plan;
using B.S.XZYData.ErrorCode;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Net.Mime;

namespace B.S.XZYData.Api.Wrter.Controllers
{
    /// <summary>
    /// 生产计划写操作控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class PlanController : ControllerBase
    {
        private readonly IMediator _mediator;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mediator">中介者</param>
        public PlanController(IMediator mediator)
        {
            _mediator = mediator;
        }

        /// <summary>
        /// 保存生产计划（主表+子表一起保存）
        /// </summary>
        /// <param name="command">保存生产计划命令</param>
        /// <returns>返回生产计划ID</returns>
        [HttpPost("save")]
        // [Authorize] // 临时移除认证，用于测试功能
        public async Task<ApiResult<int>> SavePlan([FromBody] SavePlanCommand command)
        {
            return await _mediator.Send(command);
        }

        /// <summary>
        /// 删除生产计划
        /// </summary>
        /// <param name="command">删除生产计划命令</param>
        /// <returns>删除结果</returns>
        [HttpDelete("delete")]
      
        public async Task<ApiResult<bool>> DeletePlan([FromBody] DeletePlanCommand command)
        {
            return await _mediator.Send(command);
        }

        /// <summary>
        /// 批量删除生产计划
        /// </summary>
        /// <param name="command">批量删除生产计划命令</param>
        /// <returns>批量删除结果</returns>
        [HttpDelete("batch-delete")]
       
        public async Task<ApiResult<BatchDeletePlanResult>> BatchDeletePlan([FromBody] BatchDeletePlanCommand command)
        {
            return await _mediator.Send(command);
        }

        /// <summary>
        /// 批量删除计划明细
        /// </summary>
        /// <param name="command">批量删除计划明细命令</param>
        /// <returns>删除结果</returns>
        [HttpDelete("delete-items")]
        
        public async Task<ApiResult<bool>> DeletePlanItems([FromBody] DeletePlanItemsCommand command)
        {
            return await _mediator.Send(command);
        }

        /// <summary>
        /// 导出生产计划到Excel
        /// </summary>
        /// <param name="command">导出生产计划命令</param>
        /// <returns>Excel文件</returns>
        [HttpPost("export")]

        public async Task<IActionResult> ExportPlan([FromBody] ExportPlanCommand command)
        {
            var result = await _mediator.Send(command);
            
            if (result.Code != ApiEnum.Success)
            {
                return BadRequest(result);
            }

            var fileName = $"生产计划导出_{DateTime.Now:yyyyMMdd_HHmmss}.xlsx";
            return File(result.Data!, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
        }

        /// <summary>
        /// 从Excel导入生产计划
        /// </summary>
        /// <param name="file">Excel文件</param>
        /// <param name="operateBy">操作人</param>
        /// <returns>导入结果</returns>
        [HttpPost("import")]
       
        public async Task<ApiResult<ImportPlanResult>> ImportPlan(IFormFile file, [FromForm] string operateBy)
        {
            if (file == null || file.Length == 0)
            {
                return new ApiResult<ImportPlanResult>
                {
                    Code = ApiEnum.Fail,
                    Msg = "请选择要导入的文件"
                };
            }

            // 检查文件类型
            var allowedExtensions = new[] { ".xlsx", ".xls" };
            var fileExtension = Path.GetExtension(file.FileName).ToLowerInvariant();
            if (!allowedExtensions.Contains(fileExtension))
            {
                return new ApiResult<ImportPlanResult>
                {
                    Code = ApiEnum.Fail,
                    Msg = "只支持Excel文件格式(.xlsx, .xls)"
                };
            }

            // 读取文件内容
            using var memoryStream = new MemoryStream();
            await file.CopyToAsync(memoryStream);

            var command = new ImportPlanCommand
            {
                FileBytes = memoryStream.ToArray(),
                FileName = file.FileName,
                OperateBy = operateBy
            };

            return await _mediator.Send(command);
        }

        /// <summary>
        /// 获取导入模板
        /// </summary>
        /// <returns>Excel模板文件</returns>
        [HttpGet("import-template")]
        public IActionResult GetImportTemplate()
        {
            // 创建简单的导入模板
            var templateContent = CreateImportTemplate();
            var fileName = "生产计划导入模板.xlsx";
            
            return File(templateContent, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
        }

        /// <summary>
        /// 创建导入模板
        /// </summary>
        /// <returns>模板文件字节数组</returns>
        private byte[] CreateImportTemplate()
        {
            // 创建工作簿
            var workbook = new NPOI.XSSF.UserModel.XSSFWorkbook();
            var worksheet = workbook.CreateSheet("生产计划导入模板");
            
            // 创建标题行样式
            var headerStyle = workbook.CreateCellStyle();
            headerStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.LightBlue.Index;
            headerStyle.FillPattern = NPOI.SS.UserModel.FillPattern.SolidForeground;
            
            var headerFont = workbook.CreateFont();
            headerFont.IsBold = true;
            headerStyle.SetFont(headerFont);
            
            // 设置表头
            var headers = new[] { "计划单号", "备注", "产品编号", "产品名称", "规格", "计划数量" };
            var headerRow = worksheet.CreateRow(0);
            for (int i = 0; i < headers.Length; i++)
            {
                var cell = headerRow.CreateCell(i);
                cell.SetCellValue(headers[i]);
                cell.CellStyle = headerStyle;
            }

            // 添加示例数据
            var dataRow = worksheet.CreateRow(1);
            dataRow.CreateCell(0).SetCellValue("PLAN001");
            dataRow.CreateCell(1).SetCellValue("示例计划");
            dataRow.CreateCell(2).SetCellValue("PROD001");
            dataRow.CreateCell(3).SetCellValue("示例产品");
            dataRow.CreateCell(4).SetCellValue("规格A");
            dataRow.CreateCell(5).SetCellValue(100);

            // 自动调整列宽
            for (int i = 0; i < headers.Length; i++)
            {
                worksheet.AutoSizeColumn(i);
            }

            // 将工作簿写入内存流
            using var memoryStream = new MemoryStream();
            workbook.Write(memoryStream);
            return memoryStream.ToArray();
        }
    }
} 